/*
 * @Description: 
 * @Author: liyuhao
 * @Date: 2021-06-18 10:27:14
 * @LastEditors: liyuhao
 * @LastEditTime: 2021-06-18 10:28:29
 */
type IdType = number | string | boolean

interface MapItem {
    id: IdType
    name: any

    [key: string]: any
}

interface OptionItem {
    value: any
    label: any
}

interface MapArray<T> extends Array<T> {
    toOption: () => Array<OptionItem>
    findById: (id?: IdType) => MapItem
    findByName: (name?: any) => MapItem
    getName: (id?: IdType) => string | undefined
    getId: (name?: any) => IdType | undefined
}

const _MapFuns: unknown = {
    toOption() {
        return (this as MapItem[]).map(v => ({
            value: v.id,
            label: v.name
        }))
    },
    findById(id?: IdType) {
        const [res] = (this as MapItem[]).filter(v => v.id === id)
        return res
    },
    findByName(name?: any) {
        const [res] = (this as MapItem[]).filter(v => v.name === name)
        return res
    },
    getName(id?: IdType) {
        const [res] = (this as MapItem[]).filter(v => v.id === id)
        return res && res.name
    },
    getId(name?: any) {
        const [res] = (this as MapItem[]).filter(v => v.name === name)
        return res && res.id
    }
}

const CreateEnumMap: (data: MapItem[]) => MapArray<MapItem> = data => {
    const _data = [...data]
    const proto = Object.getPrototypeOf(data)
    const _obj = Object.create(proto)
    Object.assign(_obj, _MapFuns)
    Object.setPrototypeOf(_data, _obj)
    return _data as MapArray<MapItem>
}

export default CreateEnumMap